package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.ProductDao;
import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductImpl implements ProductDao {
    @Override
    public List<ProductModel> findAll(ProductModel productModel) {
        String sql = "select * from product where 1=1 ";
        if (!"".equals(productModel.getName())) {
            sql += " and name like '%" + productModel.getName() + "%'";
        }

        sql += " order by id desc";
        sql += " limit  " + (productModel.getPageModel().getCurPage() - 1) * productModel.getPageModel().getPageSize() + "," + productModel.getPageModel().getPageSize() + " ";
        return setList(sql);
    }

    @Override
    public int getCount(ProductModel productModel) {
        String sql = "select count(*) count from product";
        ResultSet resultSet = JDBC.query(sql);
        int count = 0;
        try {
            while (resultSet.next()) {
                count = resultSet.getInt("count");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public int add(ProductModel productModel) {
        String sql = "INSERT INTO `product` " +
                "(`name`,  `price`, " +
                "`content`, `img_href`, " +
                "`create_time`) VALUES " +
                "('" + productModel.getName() + "',  '" + productModel.getPrice() + "', " +
                "'" + productModel.getContent() + "', '" + productModel.getImgHref() + "'," +
                "now());";
        return JDBC.update(sql);
    }

    @Override
    public List<ProductModel> findProductForHome() {
        String sql = "select * from product limit 2";
        return setList(sql);
    }

    private List<ProductModel> setList(String sql) {
        List<ProductModel> list = new ArrayList<>();
        ResultSet resultSet = JDBC.query(sql);
        try {
            while (resultSet.next()) {
                ProductModel model = new ProductModel();
                model.setId(resultSet.getInt("id"));
                model.setName(resultSet.getString("name"));
                model.setContent(resultSet.getString("content"));
                model.setPrice(resultSet.getFloat("price"));
                model.setIsShow(resultSet.getInt("is_show"));
                model.setIsRecommend(resultSet.getInt("is_recommend"));
                model.setUpdateTime(resultSet.getString("update_time"));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
